using System;
using MicroDal.Context;
namespace MicroDal
{
	internal static class SessionFactory
	{
		private static ISessionStorage _sessionStorrage = Construct();

		public static DataSession GetCurrent ()
		{
			var session = _sessionStorrage.GetCurrent ();
			if (session == null || session.IsDisposed)
				throw new ObjectDisposedException ("DataSession");
			return session;
		}

        public static DataSession Get(string name)
        {
            var session = _sessionStorrage.Get(name);
            if (session == null || session.IsDisposed)
                throw new ObjectDisposedException("DataSession");
            return session;
        }
		
		private static ISessionStorage Construct ()
		{
			ISessionStorage storrage;
			bool http = false;
			try
			{
				var ctxt = System.Web.HttpContext.Current;
				http = ctxt != null;
			}
			finally
			{
                if (http)
                {
                    Tracer.WriteTrace("HTTP session storage created");
                    storrage = new HttpSessionStorage();
                }
                else
                {
                    Tracer.WriteTrace("Thread session storage created");
                    storrage = new ThreadSessionStorage();
                }
			}
			return storrage;
		}
	}
}

